package com.wu.ssm.spring.mvc;


import com.wu.ssm.spring.InstanceFactory;
import com.wu.ssm.spring.ioc.*;
import com.wu.ssm.spring.utils.UploadHelper;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wzf on 2018/11/4/004.
 */

public class MyDispatcherServlet extends HttpServlet {


    private List<HandlerAdapter> handlerAdapters = new ArrayList<>();

    private HandlerInvoker handlerInvoker = InstanceFactory.getHandlerInvoker();


    @Override
    public void init(ServletConfig config) throws ServletException{
        // 我们加载那些bean
        try {
            // 初始化ioc容器（里面包含了初始化handlerMappings的过程）
            HelperLoader.init();
            // 初始化相关配置
            UploadHelper.init(config.getServletContext());
            // 初始化策略
            initStrategies();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) {
        try {
            doDispatch(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String requestMethod = request.getMethod();
        String requestPath = request.getPathInfo();

        HandlerMapping  handlerMapping = InstanceFactory.getHandlerMapping();

        Handler handler = handlerMapping.getHandler(requestMethod, requestPath);

        if(handler != null){
            //HandlerAdapter handlerAdapter = getHandlerAdapter(handler);
            //handlerAdapter.handle(handler, request, response);
        }else {
            PrintWriter out = null;
            try {
                out = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            out.write("404");
            return;
        }

        // 初始化 DataContext
        DataContext.init(request, response);
        // 调用 Handler
        handlerInvoker.invokeHandler(request, response, handler);



    }


    public HandlerAdapter getHandlerAdapter(Handler handler){
        for(HandlerAdapter adapter: this.handlerAdapters){
            if(adapter.supports(handler)){
                return adapter;
            }
        }
        return null;
    }



    protected void initStrategies() {
        //初始化handlerMappings
        initHandlerMappings();
        initHandlerAdapters();

    }

    private void initHandlerAdapters() {
        //handlerAdapters.add(new SimpleServletHandlerAdapter());
        handlerAdapters.add(new RequestMappingHandlerAdapter());
    }

    private void initHandlerMappings() {
    }

}
